﻿using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace EditorFrameWork
{
    public class SearchField: GUIBase
    {

        private int mContentIndex;
        private string m_SearchContent;
        private string[] m_SearchableContents;
        private MethodInfo mDrawAPI;
        public event Action<int> OnModeChanged;
        public event Action<string> OnValueChanged;
        public event Action<string> OnEndEdit;
        public SearchField(string searchContent, string[] searchableContents, int contentIndex)
        {
            mContentIndex = contentIndex;
            m_SearchContent = searchContent;
            m_SearchableContents = searchableContents;

            typeof(EditorGUI).GetMethod("ToolbarSearchField",
                BindingFlags.NonPublic | BindingFlags.Static,
                null,
                new Type[]
                {
                    typeof(int), typeof(Rect), typeof(string[]), typeof(int).MakeByRefType(), typeof(string)
                },
                null
            );
        }

        private int mControllId;
        public override void OnGUI(Rect position)
        {
            base.OnGUI(position);
            if (mDrawAPI != null)
            {
                mControllId = GUIUtility.GetControlID("EditorSearchField".GetHashCode(), FocusType.Keyboard, position);
                int mode = mContentIndex;
                object[] args = new object[]
                {
                    mControllId, position, m_SearchableContents, mode, m_SearchContent
                };
                string newSearchableContent = mDrawAPI.Invoke(null, args) as string;
                if ((int)args[3] != mContentIndex)
                {
                    mContentIndex = (int)args[3];
                    OnModeChanged?.Invoke(mContentIndex);
                    //OnModeChange;
                }

                if (newSearchableContent != m_SearchContent)
                {
                    m_SearchContent = newSearchableContent;
                    //OnValueChange
                    OnValueChanged?.Invoke(m_SearchContent);
                }

                Event e = Event.current;
                if (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.Escape || e.character == '\n')
                {
                    GUIUtility.keyboardControl = -1;
                    if (e.type != EventType.Repaint && e.type != EventType.Layout)
                    {
                        e.Use();
                    }
                    //OnEndEdit
                    OnEndEdit?.Invoke(m_SearchContent);
                }
            }
            
        }

        protected override void OnDispose()
        {
            
        }
    }
}